#!/bin/bash
USERNAME=$(whiptail --title "添加各服务用户" --inputbox "请输入你的用户名（将作为登录账号的用户）" 10 60 3>&1 1>&2 2>&3)
exitstatus=$?
if [ $exitstatus = 0 ]; then
    echo ""您的账户名为:" $USERNAME" > user.txt
else
    exit
fi
EMAIL=$USERNAME@ts-it.cn
NAME=$USERNAME
PASSWD=$(whiptail --title "添加各服务用户" --inputbox "请输入你的密码（将作为登录账号的密码）" 10 60 3>&1 1>&2 2>&3)

exitstatus=$?
if [ $exitstatus = 0 ]; then
    echo ""您的密码:" $PASSWD" >> user.txt
else
	exit
fi
echo "为您创建的服务包括：" >> user.txt
harbor() {
curl -u "用户名:密码" -X POST -H "Content-Type: application/json" "https://harbor.cn/api/v2.0/users" \
	--data '{
	"username": "'"$USERNAME"'",
	"email": "'"$EMAIL"'",
	"password": "'"$PASSWD"'",
	"realname": "'"$NAME"'",
	"role_id": 2
}'
}
rancher() {
curl -k --request POST \
  --url 'https://rancher:8443/v3/users' \
  --header  'Content-Type:application/json' \
  --header  'Authorization:Basic xxx' \
  --header  'Accept:application/json'\
  --data '{
    "enabled": true,
    "mustChangePassword": false,
    "name": "'"$NAME"'",
    "password": "'"$PASSWD"'",
    "principalIds": [],
    "username": "'"$USERNAME"'"
}'
}
creategitlab() {
# 发送post请求 token与url需更换为自己的
    curl -X POST -H "PRIVATE-TOKEN: xxx" "http://gitlab/api/v4/users" -H 'cache-control: no-cache' -H 'content-type: application/json' \
    -d '{ "email": "'"$EMAIL"'", "username": "'"$USERNAME"'", "password": "'"$PASSWD"'", "name": "'"$NAME"'", "skip_confirmation": "true" }'
}
createvpn() {
ssh 192.168.11.60 "/opt/openvpn/createvpn.sh $USERNAME"
scp 192.168.11.60:/root/$USERNAME.ovpn /root/test/vpn/
ssh 192.168.11.60 "mv -f /root/*.ovpn /root/vpn/"
sed -i 's\1194\65530\g' /root/test/vpn/$USERNAME.ovpn
}
removevpn(){
ssh 192.168.11.60 "tail -n +2 /etc/openvpn/server/easy-rsa/pki/index.txt | grep "^V" | cut -d '=' -f 2 | nl -s ') '"
}
jumpserver(){
python3 jumpserveradduser.py "$USERNAME" "$PASSWD" "$NAME"
}
DISTROS=$(whiptail --title "添加各服务用户" --checklist \
"选择需要添加账号的服务" 15 60 5 \
"1" "gitlab" ON \
"2" "rancher" ON \
"3" "jumpserver" ON \
"4" "vpn" ON \
"5" "harbor" ON 3>&1 1>&2 2>&3)

exitstatus=$?
if [ $exitstatus = 0 ]; then
        for i in ${DISTROS[*]}
                do
    case $i in
        \"1\")
                creategitlab
		echo "服务名：gitlab，地址：xxx" >> user.txt
;;
        \"2\")
                rancher
		echo "服务名：rancher，地址：xxx" >> user.txt
;;
        \"3\")
                jumpserver
		echo "服务名：jumpserver，地址：xxx" >> user.txt
;;
        \"4\")
		createvpn
		echo "服务名：vpn，证书见附件" >> user.txt
;;
        \"5\")
                harbor
		echo "服务名：harbor，地址：xxx" >> user.txt
;;
    esac
        done
else
    echo "You chose Cancel."
fi

#邮箱通知
python3 send_mail_fujian.py "账号$USERNAME创建成功" user.txt $EMAIL $USERNAME.ovpn
#python3 send_mail_fujian.py "账号$USERNAME创建成功" user.txt liuhuan@ts-it.cn $USERNAME.ovpn
